package ling.common;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import lombok.var;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ValidUtil {
   static Validator validator= Validation.buildDefaultValidatorFactory().getValidator();

    public static  String[] valid(Object obj) {
        var list = new ArrayList<String>();
        for (ConstraintViolation<Object> violation : validator.validate(obj)) {
            list.add(violation.getMessage() + "["+violation.getPropertyPath().toString()+"]");
        }
        return list.toArray(new String[0]);
    }
    public  static String validToStr(Object obj){
       return String.join(";\r\n",valid(obj));
    }
    public static R validToR(Object obj) {
        var err = validToStr(obj);
        if (StringUtils.isNotBlank(err))
            return R.fail(err);
        return R.ok();
    }
    public static R validList(Collection<?> objs) {
        for (Object obj : objs)
        {
            var r= validToR(obj);
            if(!R.isSuccess(r))
                return r;
        }
        return R.ok();
    }


}
